<template>
  <div class="comment-container">
    <div class="new-comment">
      <!-- 添加回复提示 -->
      <div v-if="replyingTo" class="reply-hint">
        回复 @{{ replyUserName }}
        <el-button
          type="text"
          size="mini"
          @click="cancelReply"
        >取消回复</el-button>
      </div>

      <editor v-model="newComment" :min-height="192"/>

      <el-button
        type="primary"
        size="mini"
        @click="submitComment"
        style="margin-top: 10px"
      >{{ replyingTo ? '回复' : '评论' }}</el-button>
    </div>

    <comment-item
      v-for="comment in comments"
      :key="comment.commentId"
      :comment="comment"
      :parent-author="null"
      @on-delete-success="handleCommentDeleted"
      @reply="handleReply"
    />
  </div>
</template>

<script>
import CommentItem from './CommentItem';
import { addComments } from "@/api/know/comments";

export default {
  props: ['comments', 'postId','commentType'],
  components: { CommentItem },
  data() {
    return {
      newComment: '',      // 新评论内容
      replyingTo: 0,     // 当前回复的评论ID
      replyUserName: '',   // 回复用户名
      //commentType: 0     // 评论类型：1：知识点 2 笔记 3 帖子
    }
  },
  methods:{
    handleReply(commentId, userName,commentType) {
      this.replyingTo = commentId;
      this.replyUserName = userName;
      this.commentType = commentType;
      console.log(commentType)

      this.$nextTick(() => {
        const input = this.$el.querySelector('.new-comment textarea');
        input?.focus();
        document.querySelector('.new-comment').scrollIntoView({
          behavior: 'smooth'
        });
      });
    },
    cancelReply() {
      this.replyingTo = 0;
      this.replyUserName = '';
    },
    async submitComment() {
      if (!this.newComment.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      try {
        const params = {
          infoId: this.postId,
          commentType: this.commentType,
          content: this.newComment,
          pCommentId: this.replyingTo
        }

        await addComments(params);
        this.$message.success('评论成功');
        this.newComment = '';
        this.replyingTo = null;
        this.$emit('refresh-comments');
      } catch (e) {
        console.error('评论失败', e);
      }
    },
    // 处理删除成功事件
    handleCommentDeleted() {
      this.$emit('refresh-comments');  // 向上层传递刷新事件
    }
  }
}
</script>
<style>
.new-comment {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}
.reply-hint {
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
